from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class GetForm(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        self.response.headers['Expires'] = 'Wed, 17 Sep 1975 21:32:10 GMT'
        self.response.headers['Content-Type'] = 'text/html'
        content = '''
        <html><head><title>Submit form</title>
        <script>
        function postMessage(){
            try{
                //window.parent.postMessage('[{"action": "setGwextWndTitle", "title":"Hello world. Thats absolutely impossible. yeahhhhhhh"}]', 'https://wave.google.com/');
                window.parent.postMessage('[{"action": "openGwextPopupWindow", "url":"http://google.com"}]', 'https://wave.google.com/');
            }catch(e){}
        }
        </script>
        </head>
            <body onload="postMessage()" style="background: #c0c0c0;">
                <form method="POST" action="''' + self.request.scheme + '://' + self.request.host + '''/gwext/submit">
                    <input type="text" name="query"></input>
                    <input type="submit" value="Искать"></input>
                    <input type="hidden" name="hash" value="''' + self.request.get('hash') + '''"></input>
                    <input type="hidden" name="waveId" value="''' + self.request.get('waveId') + '''"></input>
                    <input type="hidden" name="waveletId" value="''' + self.request.get('waveletId') + '''"></input>
                    <input type="hidden" name="blipId" value="''' + self.request.get('blipId') + '''"></input>
                </form>
            </body>
        </html>
        '''
        self.response.out.write(content)

class Submit(webapp.RequestHandler):
    def getHtmlLink(self, link):
        import re
        import urllib2
        if re.match('waveid://', link): return '#'
        if re.match('http://www.google.com/url\?sa=D&q=', link):
            link = link.replace('http://www.google.com/url?sa=D&q=', '')
            link = urllib2.unquote(link)
        return link
    
    def post(self):
        wave_id = self.request.get('waveId')
        wavelet_id = self.request.get('waveletId')
        blip_id = self.request.get('blipId')
        hash = self.request.get('hash')
        query_str = self.request.get('query')
        import logging
        logging.info(wave_id)
        logging.info(wavelet_id)
        logging.info(blip_id)
        import robot
        from service.settings import WAVE_CONSUMER_KEY, WAVE_CONSUMER_SECRET
        from service.settings import WAVE_PREVIEW, WAVE_SANDBOX
        
        rpc = WAVE_PREVIEW
        if wave_id.split('!')[0] == 'wavesandbox.com':
            rpc = WAVE_SANDBOX
        bot = robot.getRobotInstance()
        bot.setup_oauth(WAVE_CONSUMER_KEY, WAVE_CONSUMER_SECRET, rpc);
        from waveapi import errors
        wavelet = bot.fetch_wavelet(wave_id, wavelet_id=wavelet_id)
        type(wavelet)
        import logging
        logging.info(type(wavelet.blips))
        blip = wavelet.blips.get(blip_id)
        logging.info(blip.serialize())
        import re
        for annotation in blip.annotations:
            logging.info(annotation.serialize())
            name = annotation.name
            value = annotation.value
            if not re.match('link/', annotation.name): continue
            link = self.getHtmlLink(annotation.value)
            logging.info(link)
            if not re.match(self.request.scheme + '://' + self.request.host + '/gwext/getForm', link): continue
            import urllib2
            query = urllib2.unquote(link[link.find('?')+1:])
            logging.info(query)
            params = dict((param.split('=')[0], param.split('=')[1]) for param in query.split('&'))
            logging.info(params)
            try:
                if params['waveId'] != wave_id or params['waveletId'] != wavelet_id or params['blipId'] != blip_id:
                    continue 
            except:
                continue
            start = annotation.start
            blip.range(annotation.start, annotation.end).replace(query_str)
            logging.info(name)
            logging.info(value)
            logging.info(start)
            logging.info(annotation.serialize())
            blip.range(start, start + len(query_str)).annotate(name, value)
#            http://localhost:8080/gwext/getForm?waveId=googlewave.com!w%2BWmCWnpusD&waveletId=googlewave.com!conv%2Broot&blipId=b%2BR6ugWEDyA&hash=123
            logging.info(query)
            break
        bot.submit(wavelet)
        self.response.headers['Expires'] = 'Wed, 17 Sep 1975 21:32:10 GMT'
        self.response.headers['Content-Type'] = 'text/html'
        content = '''
        <html><head><title>Submit form</title>
        <script>
        function postMessage(){
            try{
                //window.parent.postMessage('[{"action": "closeGwextWnd"}]', 'https://wave.google.com/');
                window.parent.postMessage('[{"action": "setGwextFrameHeight", "height":"300px"}, {"action":"setGwextFrameWidth","width":"600px"}]', 'https://wave.google.com/');
            }catch(e){}
        }
        </script>
        </head>
            <body onload="postMessage()" style="background: #c0c0c0;">
            </body>
        </html>
        '''
        logging.info(content)
        self.response.out.write(content)

def run():
    app = webapp.WSGIApplication([
        ('/gwext/getForm', GetForm),
        ('/gwext/submit', Submit),
    ], debug=True)
    run_wsgi_app(app)

if __name__ == '__main__':
    run()